package com.dq.service.order.impl;

import com.dq.context.Constant;
import com.dq.exception.customException.AdminException;
import com.dq.domain.goods.Product;
import com.dq.domain.orders.Orders;
import com.dq.domain.orders.OrgOrder;
import com.dq.domain.orders.info.OrderInfo;
import com.dq.domain.org.Org;
import com.dq.domain.sys.section.SysSection;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.repository.BaseRepositories;
import com.dq.service.messsge.ApprovalMessageService;
import com.dq.service.order.BaseOrgOrderService;
import com.dq.service.section.SysSectionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liuhui
 * @date 2019/12/2 0002 11:20:41
 */
@Service
public class BaseOrgOrderServiceImpl extends BaseRepositories implements BaseOrgOrderService {
    @Autowired
    private ApprovalMessageService approvalMessageService;
    @Autowired
    private SysSectionService sysSectionService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void orgOrderAdd(List<OrgOrder.OrgOrderAdd> orgOrderAddList, Org org, SysUser staffUser) throws AdminException {
        BigDecimal totalAmount = BigDecimal.ZERO;
        List<OrderInfo> orderInfoList = new ArrayList<>();
        List<Long> longList = new ArrayList<>();
        Map<Long,Long> map = new HashMap<>();
        orgOrderAddList.forEach(orgOrderAdd -> {longList.add(orgOrderAdd.getProductId());map.put(orgOrderAdd.getProductId(),orgOrderAdd.getNum());});
        List<Product> productList = baseProductRepository.findByIdIn(longList);
        for (Product product:productList) {
            Long num = map.get(product.getId());
            BigDecimal amount  = product.getPrice().multiply(new BigDecimal(num));
            OrderInfo orderInfo =new OrderInfo(product,num,amount);
            orderInfo.setGoods(product.getGoods());
            orderInfoList.add(orderInfo);
            totalAmount = totalAmount.add(amount);
        }
        OrgOrder orgOrder = new OrgOrder(staffUser, org, totalAmount, OrgOrder.OrgOrderStatus.submitPass);
        if(StringUtils.isBlank(orgOrder.getOrdersNo())) {
            orgOrder.setOrdersNo(Orders.generyDatetimeAndRandomNum(Constant.ORDERS_SUFF_COUNT));
        }

        Long payGoodsNum = 0L;
        for (OrderInfo orderInfo : orderInfoList) {
            payGoodsNum = payGoodsNum + orderInfo.getNumber();
        }
        orgOrder.setPayGoodsNum(payGoodsNum);
        orgOrder.setCateNum(Long.parseLong(String.valueOf(orderInfoList.size())));

        // 库存逻辑
        SysSection numberOne = sysSectionService.getNumberOne();
        for (OrderInfo orderInfo : orderInfoList) {
            Long stock = goodsService.productStock(orderInfo.getProduct().getId(), numberOne.getId());
            if(stock < orderInfo.getNumber()) {
                throw new AdminException(orderInfo.getProduct().getGoods().getGoodsName() + ", 库存不足");
            }
            /// 扣减库存，仓库确认减库存
            // 自动生成 boss 库存变动记录, 修改对应商品库存
//            orgStockChangeService.orderInfoStock(nullSysDepts.get(0), orderInfo, StockChangeRecord.ChangeDirection.reduce, StockChangeRecord.ChangeType.adjust);
        }

        OrgOrder save = baseOrgOrderRepository.save(orgOrder);
        List<OrderInfo> newOrderInfoList = new ArrayList<>();
        orderInfoList.forEach(orderInfo ->{ orderInfo.setOrders(orgOrder);newOrderInfoList.add(orderInfo);});
        baseOrderInfoRepository.saveAll(newOrderInfoList);

        // 发送采购消息, 异常不影响采购单生成
        try {
            approvalMessageService.messageToBoss(save.getId());
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
